<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      @click-left="$router.push('/')"
    ></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="loading">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-else-if="article.title">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ article.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="article.aut_photo"
          />
          <div slot="title" class="user-name">{{ article.aut_name }}</div>
          <div slot="label" class="publish-date">
            {{ article.pubdate | relativeTime }}
          </div>
          <!-- 组件之间传值需要修改数据的时候可以用v-model来进行传递他内部会帮你监听事件,
          他默认传过去的值名字叫value ,事件名叫input ,可以通过model属性进行修改 -->
          <!-- <followUser
            class="follow-btn"
            :isFollowed="article.is_followed"
            :followedId="article.aut_id"
            @update-is_followed="article.is_followed = $event"
          /> -->
          <!-- 引入关注用户的组件 -->
          <FollowUser
            class="follow-btn"
            v-model="article.is_followed"
            :followedId="article.aut_id"
          />
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <!-- ref用于获取元素指定dom操作 -->
        <div
          class="article-content markdown-body"
          v-html="article.content"
          ref="article-content"
        ></div>
        <van-divider>正文结束</van-divider>
        <!-- 评论列表模块 -->
        <!-- 传递当前评论的id 文章评论的type值是a,是默认值,也可以不传

        onload-success是把文章评论列表里面的列表数量传过来,然后渲染到页面
        commentList是利用状态提升实现兄弟组件之前的传值
          -->
        <CommentList
          :source="article.art_id"
          type="a"
          @onload-success="totalCommentCount = $event.total_count"
          :list="commentList"
          @reply-click="replyComment"
        />
        <!-- 点击写评论弹出弹出层 -->
        <van-popup v-model="isCommentShow" position="bottom">
          <!-- 写评论的模板   这里的评论是对文章进行评论 把当前文章的id传过去  然后把返回回来的数据添加到评论列表中进行渲染-->
          <CommentPost :target="article.art_id" @commentSuccess="successList" />
        </van-popup>
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败：404 -->
      <div class="error-wrap" v-else-if="errStatus === 404">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除！</p>
      </div>
      <!-- /加载失败：404 -->

      <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
      <div class="error-wrap" v-else>
        <van-icon name="failure" />
        <p class="text">内容加载失败！</p>
        <van-button class="retry-btn" @click="loadingSearch"
          >点击重试</van-button
        >
      </div>
      <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>

    <!-- 底部区域 -->
    <div class="article-bottom" v-if="article.title">
      <van-button
        class="comment-btn"
        type="default"
        round
        size="small"
        @click="isCommentShow = true"
        >写评论</van-button
      >
      <van-icon name="comment-o" :badge="totalCommentCount" color="#777" />
      <!-- 文章收藏 -->
      <CollectArticle
        class="btn-item"
        v-model="article.is_collected"
        :articleId="article.art_id"
      />
      <!-- 文章点赞 -->
      <LikeArticle v-model="article.attitude" :articleId="article.art_id" />
      <van-icon name="share" color="#777777"></van-icon>
      <!-- 评论的回复框 -->
      <van-popup v-model="isApplyShow" position="bottom" style="height:93%;">
        <!-- 回复评论的模板 -->
        <!-- v-if是用来控制页面刷新的,随着弹层关闭打开进行时时更新 -->
        <CommentReply
          v-if="isApplyShow"
          :comment="replyComments"
          @close="isApplyShow = false"
        />
        <!--replyComments 是通过子组件一层一层传回来的当前评论项,然后传递给回复评论模板 -->
      </van-popup>
    </div>
    <!-- /底部区域 -->
  </div>
</template>

<script>
// 传入文章id获取文章详情
import { getArticleById } from '@/api/article'
import { ImagePreview } from 'vant'
// 引入格式化正文格式的样式
import './github-markdown.css'

import FollowUser from '@/components/follow_user/index.vue'
import CollectArticle from '@/components/collect-article/index.vue'
import LikeArticle from '@/components/likeArticle/index.vue'

import CommentList from './components/comment-list.vue'
import CommentPost from './components/comment-post.vue'
import CommentReply from './components/comment-reply.vue'
export default {
  name: 'ArticleIndex',
  components: {
    FollowUser,
    CollectArticle,
    LikeArticle,
    CommentList,
    CommentPost,
    CommentReply
  },
  // 给所有的后代组件提供数据  所有的后代都可以通过inject属性获取到文章id
  provide: function() {
    return {
      articleId: this.articleId
    }
  },
  props: {
    articleId: {
      // 如果是大数字的时候,就会是一个对象
      // 主页点击跳转的时候是数字行
      // 直接用路径按回车请求的时候是字符串
      type: [Number, String, Object],
      required: true
    }
  },
  data() {
    return {
      article: {}, // 文章详情
      loading: true,
      errStatus: 0,
      followLoading: false,
      totalCommentCount: 0, // 评论总数
      isCommentShow: false, // 评论框
      commentList: [], // 评论列表
      isApplyShow: false, // 评论回复框
      replyComments: {} // 当前评论项
    }
  },
  computed: {},
  watch: {},
  created() {
    this.loadingSearch()
  },
  mounted() {},
  methods: {
    async loadingSearch() {
      // 因为需要重新加载,所有页面一打开就要刷新
      this.loading = true
      try {
        // 这个地方由于大数字问题,返回的数据不对,会报404的错
        const { data } = await getArticleById(this.articleId)
        this.article = data.data
        this.loading = false
        // 当数据加载完毕之后调用这个方法执行图片预览
        this.$nextTick(() => {
          this.previewImage()
        })
      } catch (err) {
        // 判断失败的状态,如果是404导致的就显示404的错误提示,如果不是就提示刷新
        if (err.response && err.response.status === 404) {
          this.errStatus = 404
        }
        this.$toast('获取失败')
      }
      // 不管是不是404导致的错误都要关掉loading
      this.loading = false
    },
    previewImage() {
      const articleContent = this.$refs['article-content']
      const imgs = articleContent.querySelectorAll('img')
      const images = []
      imgs.forEach((img, index) => {
        images.push(img.src)
        img.onclick = function() {
          ImagePreview({
            images,
            startPosition: index
          })
        }
      })
    },
    successList(data) {
      this.$toast.loading({
        message: '发布中...',
        forbidClick: true, // 禁用背景点击
        duration: 0 // 持续时间，默认 2000，0 表示持续展示不关闭
      })
      // 关闭弹框
      this.isCommentShow = false
      // 把数据添加进去到评论列表中
      this.commentList.unshift(data.new_obj)
      this.$toast.success('发布成功')
    },
    replyComment(comment) {
      this.replyComments = comment
      this.isApplyShow = true
    }
  }
}
</script>

<style scoped lang="less">
.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
    /deep/ .van-popup {
      padding-bottom: 100px;
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>
